package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioClient  minioClient;
    @Autowired
    private MinioProperties  minioProperties;
    @Override
    public String upload(MultipartFile file) {
        //创建Bucket
        createBucket();
        //上传图片
        String dir = new SimpleDateFormat("/yyyy/MM/").format(new Date());
        //2.2 使用uuid.jpg
        String uuid = UUID.randomUUID().toString().replace("-","");
        //2.3获取文件类型   xxxxx.jpg  动态截取字符串
        String fileName = file.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        fileName = uuid + fileType;

        //2024/06/uuid.jpg
        String realFilePath = dir + fileName;
        //3.实现文件上传
        try {
            String contentType = file.getContentType();
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .contentType(contentType)
                    .stream(file.getInputStream(),file.getSize(),-1)
                    .object(realFilePath)
                    .build();
            minioClient.putObject(putObjectArgs);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        //http://192.168.126.128/lease/2024/06/uuid.jpg
        String url = minioProperties.getEndpoint() + "/" +minioProperties.getBucketName() + realFilePath;

        return url;
    }
    public void createBucket(){
        try {
            BucketExistsArgs build = BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build();
            if(!minioClient.bucketExists(build)){
                MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build();
                minioClient.makeBucket(makeBucketArgs);

                //设置策略
                String config = """
                         {
                                       "Statement" : [ {
                                         "Action" : "s3:GetObject",
                                         "Effect" : "Allow",
                                         "Principal" : "*",
                                         "Resource" : "arn:aws:s3:::%s/*"
                                       } ],
                                       "Version" : "2012-10-17"
                         }
                         """.formatted(minioProperties.getBucketName());;
                SetBucketPolicyArgs setBucketPolicyArgs = SetBucketPolicyArgs.builder().bucket(minioProperties.getBucketName())
                        .config(config).build();
                minioClient.setBucketPolicy(setBucketPolicyArgs);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
